//
//  HYFileDownloadService.m
//  VideoFileDownloadDemo
//
//  Created by liguoqing on 2023/8/25.
//

#import "HYFileDownloadService.h"
#import "HYFileDownloadTask.h"
#import <HYDownloader/HYBriefDownloadTaskManager.h>
#import <HYDownloader/HYBriefDownloadHelper.h>

@interface HYFileDownloadService ()

@property (nonatomic, copy) NSString *downloadIDPrefix;

@end

@implementation HYFileDownloadService

#pragma mark - 单例
+ (HYFileDownloadService *)sharedInstance
{
    static HYFileDownloadService *sharedInstance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[super allocWithZone:NULL] init];
        sharedInstance.downloadIDPrefix = @"http";
        [sharedInstance initDownloadTasks];
    });
    return sharedInstance;
}

+ (id)allocWithZone:(NSZone *)zone
{
    return [HYFileDownloadService sharedInstance];
}

+ (id)copy
{
    return [HYFileDownloadService sharedInstance];
}

// 初始化下载任务
- (void)initDownloadTasks
{
    NSArray *dbDatas = [HYBriefDownloadHelper loadTaskModelsFromDB:[HYFileDownloadTask class]];
    
    NSMutableArray *downloadedTasks = [NSMutableArray new];
    [dbDatas enumerateObjectsUsingBlock:^(HYFileDownloadTask *task, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([task.downloadID hasPrefix:self.downloadIDPrefix]) {
            [downloadedTasks addObject:task];
        }
    }];
    [[HYBriefDownloadTaskManager sharedInstance] loadInitTasks:downloadedTasks];
    
    NSLog(@"[下载] - 设置文件下载任务%ld个", (long)downloadedTasks.count);
}

#pragma mark -查找或创建一个下载
- (HYFileDownloadTask *)findOrCreateOneTaskWithDownloadID:(NSString *)downloadID
                                                downloadURL:(NSString *)downloadURL
                                                   fileName:(NSString *)fileName
{
    HYFileDownloadTask *task = (HYFileDownloadTask *)[[HYBriefDownloadTaskManager sharedInstance] findDLDownloadTaskWithDownloadID:downloadID];
    if (!task) {
        task = [self createOneTaskWithWithDownloadID:downloadID
                                         downloadURL:downloadURL
                                            fileName:fileName];
        [[HYBriefDownloadTaskManager sharedInstance] addOneTask:task];
    }
    // 修改下载状态
    [task checkStatus];
    
    return task;
}
// 创建下载任务
- (HYFileDownloadTask *)createOneTaskWithWithDownloadID:(NSString *)downloadID
                                              downloadURL:(NSString *)downloadURL
                                                 fileName:(NSString *)fileName
{
    return [[HYFileDownloadTask alloc] initWithDownloadID:downloadID
                                                originalUrl:downloadURL
                                                 currentUrl:downloadURL
                                                   filePath:[HYFileManager videoDownloadPathWithFileName:fileName]
                                               tempFilePath:[HYFileManager tempSavePathWithFileName:fileName]];
}


@end
